import React, { useState } from "react";
import Tools from "../component/Tools";
import { Table, Input, InputNumber, Form, Typography, Popconfirm } from "antd";
import "./TableEdit.css";
import { Checkbox } from "antd";
import { useParams } from "react-router-dom";

interface Item {
  key: string;
  name: string;
  dataType: string;
  isUnsigned: boolean;
  isNull: boolean;
  isPrimary: boolean;
  remark: string;
}

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: "number" | "text";
  record: Item;
  index: number;
  children: React.ReactNode;
}

const EditableCell: React.FC<EditableCellProps> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputMap = {
    text: <Input />,
    boolean: <Checkbox />,
  };
  const inputNode = inputMap[inputType];

  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{ margin: 0 }}
          valuePropName={inputType === "text" ? "value" : "checked"}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

function TableEdit() {
  const [editingKey, setEditingKey] = useState("1");
  const isEditing = (record: Item) => record.key === editingKey;
  const [form] = Form.useForm();
  const params = useParams();
  const [data, setData] = useState<Item[]>(
    params.action === "create"
      ? [
          {
            key: "1",
            name: "",
            dataType: "",
            isUnsigned: false,
            isNull: false,
            isPrimary: false,
            remark: "",
          },
        ]
      : []
  );

  const edit = (record: Partial<Item> & { key: React.Key }) => {
    form.setFieldsValue({ ...record });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey("");
  };

  const save = async (key: React.Key) => {
    try {
      const row = (await form.validateFields()) as Item;
      console.log(row);
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        setData(newData);
        setEditingKey("");
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey("");
      }
      console.log(newData);
    } catch (errInfo) {
      console.log("Validate Failed:", errInfo);
    }
  };
  const columns = [
    {
      title: "字段",
      dataIndex: "name",
      dataType: "text",
      editable: true,
    },
    {
      title: "类型",
      width: "150px",
      dataIndex: "dataType",
      dataType: "text",
      editable: true,
    },
    {
      title: "长度/值",
      width: "150px",
      dataIndex: "limit",
      dataType: "text",
      editable: true,
    },
    {
      title: "无符号？",
      dataIndex: "isUnsigned",
      dataType: "boolean",
      width: "120px",
      editable: true,
      render(value: any) {
        return value ? "是" : "否";
      },
    },
    {
      title: "可空？",
      dataIndex: "isNull",
      dataType: "boolean",
      width: "120px",
      editable: true,
      render(value: any) {
        return value ? "是" : "否";
      },
    },
    {
      title: "主键？",
      dataIndex: "isPrimary",
      dataType: "boolean",
      width: "120px",
      editable: true,
      render(value: any) {
        return value ? "是" : "否";
      },
    },
    {
      title: "备注",
      dataIndex: "remark",
      dataType: "text",
      editable: true,
    },
    {
      title: "操作",
      dataIndex: "operation",
      width: "150px",
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{ marginRight: 8, color: "#fff" }}
            >
              Save
            </Typography.Link>
            <Typography.Link onClick={() => cancel()} style={{ color: "#fff" }}>
              Cancel
            </Typography.Link>
            {/* <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm> */}
          </span>
        ) : (
          <span>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => edit(record)}
              style={{ marginRight: 8, color: "#fff" }}
            >
              Edit
            </Typography.Link>
            <Typography.Link
              disabled={editingKey !== ""}
              onClick={() => edit(record)}
              style={{ color: "#fff" }}
            >
              Delete
            </Typography.Link>
          </span>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        inputType: col.dataType,
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  const components = {
    body: {
      cell: EditableCell,
    },
  };

  const saveTable = () => {
    window.electronAPI.createTable(data);
  };

  const addRow = () => {
    const newData = [...data];
    const newRow = {
      key: (data.length + 1).toString(),
      name: "",
      dataType: "",
      limit: "",
      isUnsigned: false,
      isNull: false,
      isPrimary: false,
      remark: "",
    };
    newData.push(newRow);
    setData(newData);
    setEditingKey(newRow.key);
  };

  return (
    <>
      <Tools
        items={[
          {
            name: "保存",
            onClick: saveTable,
          },
          {
            name: "新增一行",
            onClick: addRow,
          },
        ]}
      />
      <Form form={form} component={false} initialValues={data[0]}>
        <Table
          className="table-edit"
          components={components}
          dataSource={data}
          columns={mergedColumns}
          pagination={false}
        ></Table>
      </Form>
    </>
  );
}

export default TableEdit;
